/**
	httpsession.cpp
	~~~~~~~~~~~~~~~~~~~~~~~~~


	Copyright (c) 2007-2008 <ptthippo@gmail.com>

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/
#include "../common/config.h"
#include <boost/algorithm/string.hpp>
#include <boost/bind.hpp>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <sstream>
#include "httpsession.h"
#include "httpproxy.h"

#define BUFFER_SIZE 2048

using namespace std;
using namespace log4cxx;
namespace ba = boost::algorithm;
using boost::asio::ip::tcp;

unsigned long HTTPSession::m_session_counter = 0L;

HTTPSession::HTTPSession(boost::shared_ptr<tcp::socket> clientsock,
						boost::shared_ptr<tcp::socket> serversock)
						: m_clientsock(clientsock),
						m_serversock(serversock),
						m_client_readbuffer(new char[BUFFER_SIZE]),
						m_server_readbuffer(new char[BUFFER_SIZE]),
						m_server_pending_read(false),
						m_server_pending_write(false),
						m_client_pending_read(false),
						m_client_pending_write(false),
						m_terminating(false),
						m_logger(Logger::getLogger("httpproxy"))
{
	++m_session_counter;
}

HTTPSession::~HTTPSession()
{
	delete m_client_readbuffer;
	delete m_server_readbuffer;

	--m_session_counter;
}

unsigned long HTTPSession::getSessionCounter()
{
	return m_session_counter;
}

void
HTTPSession::Initialize(const string & method, const string & protocol, const string & host, const string & path,
					const string & version, map<string, hippolib::httpheader, hippolib::HeaderKeyComparer> headers,
					const string & hostname, bool is_via_proxy, boost::asio::streambuf & remaining_buffer,
					boost::system::error_code & error)
{

	m_server_endpoint = m_serversock->remote_endpoint(error);
	if(error)
	{
		LOG4CXX_INFO(m_logger, string("get server peer error: ") + error.message());
		return;
	}


	m_client_endpoint = m_clientsock->remote_endpoint(error);
	if(error)
	{
		LOG4CXX_INFO(m_logger, string("get client peer error: ") + error.message());
		return;
	}
	
	if(ba::iequals(method, "connect"))
	{
		boost::asio::write(*m_clientsock, boost::asio::buffer(HTTPProxy::DEFAULT_SSL_RESPONSE),
						boost::asio::transfer_all(), error);
		if(error)
			return;
	}
	else
	{
		ostringstream request_stream;
		map<string, hippolib::httpheader, hippolib::HeaderKeyComparer>::iterator iter;

		if(is_via_proxy)
			request_stream << method.c_str() << " " << protocol << "://" << host << path.c_str() << " HTTP/1.0\r\n";
		else
			request_stream << method.c_str() << " " << path.c_str() << " HTTP/1.0\r\n";
		
		iter = headers.find("host");
		if(iter == headers.end())
		{
			LOG4CXX_INFO(m_logger, boost::format("cannot get host header from %s:%d to %s:%d") %
				m_client_endpoint.address().to_string() % m_client_endpoint.port() %
				m_server_endpoint.address().to_string() % m_server_endpoint.port());
			error = boost::asio::error::invalid_argument;
			return;
		}
		request_stream << "Host: " << iter->second.getValue().c_str() << "\r\n";
		headers.erase(iter);

		request_stream << "Connection: Close\r\n";
		
		for(iter = headers.begin(); iter != headers.end(); iter++)
			request_stream << iter->second.getString().c_str() << "\r\n";

		// write Via header
		string::size_type version_index;
		if((version_index = version.find('/', 0)) != string::npos)
		{
			request_stream << "Via: " << version.substr(version_index+1).c_str() << " " <<
				hostname.c_str() << " (" << HTTPProxy::PACKAGE_NAME.c_str() << "/" <<
				HTTPProxy::PACKAGE_VERSION.c_str() << ")\r\n";
		}
		
		request_stream << "\r\n";

		// write client headers to the remote server
		boost::asio::write(*m_serversock, boost::asio::buffer(request_stream.str()), boost::asio::transfer_all(), error);
		if(error)
		{
			LOG4CXX_INFO(m_logger, boost::format("cannot write headers from %s:%d to %s:%d") %
							m_client_endpoint.address().to_string() % m_client_endpoint.port() %
							m_server_endpoint.address().to_string() % m_server_endpoint.port());
			return;
		}

		// Is this a POST message?
		if((iter = headers.find("content-length")) != headers.end())
		{
			size_t length;
			try { length = boost::lexical_cast<size_t>(iter->second.getValue());}
			catch(...)
			{
				LOG4CXX_INFO(m_logger, boost::format("Content-Length field error: %s, from %s:%d to %s:%d") %
							iter->second.getValue() %
							m_client_endpoint.address().to_string() % m_client_endpoint.port() %
							m_server_endpoint.address().to_string() % m_server_endpoint.port());
				error = boost::asio::error::invalid_argument;
				return;
			}

			char *buff = new char[length];
			int remaining_len = length;
			int cur_index = 0;
			if(remaining_buffer.size() > 0)
			{
				istream istrm(&remaining_buffer);
				streamsize len = istrm.readsome(buff, remaining_len);
				remaining_len -= len;
				cur_index += len;
			}
			
			if(remaining_len > 0)
			{
				boost::asio::read(*m_clientsock, boost::asio::buffer(buff+cur_index, remaining_len),
								boost::asio::transfer_at_least(remaining_len), error);
				if(error)
				{
					LOG4CXX_INFO(m_logger, boost::format("read length %d content error from %s:%d to %s:%d") %
								remaining_len %
								m_client_endpoint.address().to_string() % m_client_endpoint.port() %
								m_server_endpoint.address().to_string() % m_server_endpoint.port());
					delete buff;
					return;
				}
			}

			boost::asio::write(*m_serversock, boost::asio::buffer(buff, length), boost::asio::transfer_all(), error);
			if(error)
			{
				LOG4CXX_INFO(m_logger, boost::format("cannot write content from %s:%d to %s:%d") %
							m_client_endpoint.address().to_string() % m_client_endpoint.port() %
							m_server_endpoint.address().to_string() % m_server_endpoint.port());
				delete buff;
				return;
			}

			delete buff;
		}
	}

	m_server_pending_read = true;
	m_client_pending_read = true;
	
	m_serversock->async_read_some(boost::asio::buffer(m_server_readbuffer, BUFFER_SIZE),
										boost::bind(&HTTPSession::handle_server_read, this,
										boost::asio::placeholders::error,
										boost::asio::placeholders::bytes_transferred));
	m_clientsock->async_read_some(boost::asio::buffer(m_client_readbuffer, BUFFER_SIZE),
										boost::bind(&HTTPSession::handle_client_read, this,
										boost::asio::placeholders::error,
										boost::asio::placeholders::bytes_transferred));
}

void
HTTPSession::terminate()
{
	boost::system::error_code err;

	m_clientsock->cancel(err);
	m_serversock->cancel(err);
	m_serversock->shutdown(tcp::socket::shutdown_both, err);
	m_clientsock->shutdown(tcp::socket::shutdown_both, err);

	unsigned int elapsed_time = 0;
	while(m_server_pending_read || m_server_pending_write ||
			m_client_pending_read || m_client_pending_write)
	{
		hippolib::thread::sleep(100);
		elapsed_time += 100;

		if(elapsed_time % 10000 == 0)
		{
			LOG4CXX_INFO(m_logger,
				boost::format("session pending - %s:%d=>%s:%d; SR:%d, SW:%d, CR:%d, CW:%d") %
				m_client_endpoint.address().to_string() % m_client_endpoint.port() %
				m_server_endpoint.address().to_string() % m_server_endpoint.port() %
				(int)m_server_pending_read % (int)m_server_pending_write %
				(int)m_client_pending_read % (int)m_client_pending_write);
		}
	}

	
	m_serversock->close(err);
	m_clientsock->close(err);
		
	delete this;
}

void
HTTPSession::handle_server_write(const boost::system::error_code & error, size_t bytes_transferred)
{
	if(m_terminating)
	{
		m_server_pending_write = false;
		return;
	}
	
	if(!error)
	{
		m_client_pending_read = true;
		m_clientsock->async_read_some(boost::asio::buffer(m_client_readbuffer, BUFFER_SIZE),
										boost::bind(&HTTPSession::handle_client_read, this,
										boost::asio::placeholders::error,
										boost::asio::placeholders::bytes_transferred));
		m_server_pending_write = false;
	}
	else
	{
		boost::mutex::scoped_lock *lock = new boost::mutex::scoped_lock(m_term_mutex);
		if(m_terminating)
		{
			delete lock;
			m_server_pending_write = false;
			return;
		}
		else
		{
			m_terminating = true;
			delete lock;
			m_server_pending_write = false;
			terminate();
		}
	}
}

void
HTTPSession::handle_client_write(const boost::system::error_code & error, size_t bytes_transferred)
{
	if(m_terminating)
	{
		m_client_pending_write = false;
		return;
	}
		
	if(!error)
	{
		m_server_pending_read = true;
		m_serversock->async_read_some(boost::asio::buffer(m_server_readbuffer, BUFFER_SIZE),
										boost::bind(&HTTPSession::handle_server_read, this,
										boost::asio::placeholders::error,
										boost::asio::placeholders::bytes_transferred));
		m_client_pending_write = false;
	}
	else
	{
		boost::mutex::scoped_lock *lock = new boost::mutex::scoped_lock(m_term_mutex);
		if(m_terminating)
		{
			delete lock;
			m_client_pending_write = false;
			return;
		}
		else
		{
			m_terminating = true;
			delete lock;
			m_client_pending_write = false;
			terminate();
		}
	}
}

void
HTTPSession::handle_server_read(const boost::system::error_code & error, size_t bytes_transferred)
{
	if(m_terminating)
	{
		m_server_pending_read = false;
		return;
	}
	
	if(!error)
	{
		m_client_pending_write = true;
		boost::asio::async_write(*m_clientsock, boost::asio::buffer(m_server_readbuffer, bytes_transferred),
								boost::asio::transfer_all(),
								boost::bind(&HTTPSession::handle_client_write, this, boost::asio::placeholders::error,
											boost::asio::placeholders::bytes_transferred));
		m_server_pending_read = false;
	}
	else
	{
		boost::mutex::scoped_lock *lock = new boost::mutex::scoped_lock(m_term_mutex);
		if(m_terminating)
		{
			delete lock;
			m_server_pending_read = false;
			return;
		}
		else
		{
			m_terminating = true;
			delete lock;
			m_server_pending_read = false;
			terminate();
		}
	}
}

void
HTTPSession::handle_client_read(const boost::system::error_code & error, size_t bytes_transferred)
{
	if(m_terminating)
	{
		m_client_pending_read = false;
		return;
	}
	
	if(!error)
	{
		m_server_pending_write = true;
		boost::asio::async_write(*m_serversock, boost::asio::buffer(m_client_readbuffer, bytes_transferred),
								boost::asio::transfer_all(),
								boost::bind(&HTTPSession::handle_server_write, this, boost::asio::placeholders::error,
											boost::asio::placeholders::bytes_transferred));
		m_client_pending_read = false;
	}
	else
	{
		boost::mutex::scoped_lock *lock = new boost::mutex::scoped_lock(m_term_mutex);
		if(m_terminating)
		{
			delete lock;
			m_client_pending_read = false;
			return;
		}
		else
		{
			m_terminating = true;
			delete lock;
			m_client_pending_read = false;
			terminate();
		}
	}
}

